package com.ynjt.view;

import com.ynjt.model.Calculator;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

//界面处理
public class CalculatorFrame {

    final private JFrame frame;            //顶级窗口
    final private JTextField number;
    final private JPanel panel;
    private static String expression ="";  //输入的数据转划为字符串

    public CalculatorFrame(){
        frame = new JFrame("Calculator");
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);       //单击窗口的关闭按钮时程序执行的操作
        frame.setSize(300,300);
        frame.setLocationRelativeTo(null);                          //相对于指定组件的位置，null为屏幕中央

        number = new JTextField();
        number.setEditable(false);
        //number.setSize(500,100);
        frame.add(number,BorderLayout.NORTH);

        panel = new JPanel();
        panel.setLayout(new GridLayout(6,3));
        frame.add(panel,BorderLayout.CENTER);


        for(int i =1;i<10;i++){
            addButton(String.valueOf(i));
        }

        addButton("+");
        addButton("0");
        addButton("-");
        addButton("*");
        addButton("C");
        addButton("/");
        addButton("(");
        addButton(")");

        final JButton equal = new JButton("=");
        equal.setActionCommand("=");
        equal.addActionListener(new ActionListener() {
            @Override
            public void actionPerformed(ActionEvent e){
                number.setText(""+new Calculator().calculating(expression)); //显示计算得到的结果
                expression = "";            //  计算后整个输入清空
            }
        });
        panel.add(equal);
        frame.add(panel);
        frame.setResizable(false);      //设置窗口大小不可改变
        frame.setVisible(true);
    }

    /*当不为输入不为“C”和“=”时，将输入转化为字符串,为“C”时清空输入*/
    private void addButton(final String name ){
        final JButton temp = new JButton(name);
        temp.setActionCommand(name);
        if(!"C".equals(name))
            temp.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    expression += name;
                    number.setText(expression);

                }
            });
        else
            temp.addActionListener(new ActionListener() {
                @Override
                public void actionPerformed(ActionEvent e) {
                    expression="";
                }
            });
        panel.add(temp);
    }
}